package com.ws.shop.interceptor;

import java.util.Arrays;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ws.shop.action.admin.BaseAdminAction;
import com.ws.shop.entity.AdminUser;
import com.ws.shop.util.CommonUtil;
import com.ws.shop.util.StringUtil;

/**
 * 拦截器 - 保存用户请求链接及参数
 */

public class AdminRequestLogInterceptor extends HandlerInterceptorAdapter {

	private static final long serialVersionUID = 2365641900033439481L;
	private static Logger log = Logger.getLogger(AdminRequestLogInterceptor.class);

	public boolean preHandle(HttpServletRequest request,   
            HttpServletResponse response, Object handler) throws Exception {
		HttpSession session = request.getSession(false);
		AdminUser user = BaseAdminAction.getLoginAdmin(session);
		StringBuilder sb = new StringBuilder();
		String uri = request.getRequestURI();
		String ip = CommonUtil.getIpAddrByRequest(request);
		sb.append("{").append(ip).append("}{");
		if(user == null){
			sb.append("nologin}{");
		}else{
			sb.append(user.getUsername()).append("}{");
		}
		sb.append(request.getMethod()).append(" ").append(uri).append("}{");
		Map parameters = request.getParameterMap();
		Object[] arr = null;
		for (Object key : parameters.keySet()) {
			arr = (Object[])parameters.get(key);
			if(arr != null && arr instanceof String[]){
				sb.append(key).append("=").append(Arrays.toString(arr));
			}
		}
		sb.append("}");
		log.info(sb.toString());
        return true;
    }   
	

}
